﻿using MediatR;
using T.ApprovalRecord;
using T.Materials.API.Application.Command.MaterialStoreCommand;
using T.Materials.Repository.MaterialsInterface;
using static T.Materials.Domain.Enum.Enums;

namespace T.Materials.API.Application.CommandHandler.MaterialStoreCommandHandler
{
    /// <summary>
    /// 更新审批状态命令处理器
    /// </summary>
    public class UpdadteApprovalStatusCommandHandler : IRequestHandler<UpdadteApprovalStatusCommand, int>
    {

        /// <summary>
        /// 物资与入库仓储接口
        /// </summary>
        protected readonly IMaterialStoreRepository materialStoreRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="materialStoreRepository">物资与入库仓储接口</param>
        public UpdadteApprovalStatusCommandHandler(IMaterialStoreRepository materialStoreRepository)
        {
            this.materialStoreRepository = materialStoreRepository;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="InvalidOperationException"></exception>
        public async Task<int> Handle(UpdadteApprovalStatusCommand request, CancellationToken cancellationToken)
        {
            var res = await materialStoreRepository.GetModelAsync(request.MaterialStoreId);

            ApprovalRecordd approvalRecord;
            if (res.ApprovalStatus == ApprovalStatus.待提交)
            {
                res.ApprovalStatus = ApprovalStatus.待审批;
            }
            else if (res.ApprovalStatus == ApprovalStatus.已拒绝)
            {
                res.ApprovalStatus = ApprovalStatus.待审批;
            }
            else
            {
                // 处理其他状态（如果需要）
                throw new InvalidOperationException("未知的审批状态");
            }
            return await materialStoreRepository.UpdateAsync(res);
        }
    }
}
